#!/bin/bash

# =====================================================
# 工具函数：从配置文件读取值
# =====================================================


# ===== 可配置区（复制脚本时只需修改这里,只改这一行）=======
export PROJECT_CONF_FILE="ai-img-classify-server.conf"
# ======================================================

get_config_value() {
    local config_file="$1"
    local section="$2"
    local key="$3"

    if [[ ! -f "$config_file" ]]; then
        echo "❌ 错误：配置文件 $config_file 不存在" >&2
        exit 1
    fi

    local value=$(awk -v section="$section" -v key="$3" '
    BEGIN { in_section=0 }
    /^\[.*\]/ { in_section=0 }
    $0 ~ "^\\[" section "\\]" { in_section=1; next }
    in_section && $0 ~ "^" key "[[:space:]]*=" {
        gsub(/^[^=]*=[[:space:]]*/, "", $0)
        gsub(/[[:space:]]*$/, "", $0)
        gsub(/[#;].*/, "", $0)
        print $0
        found=1
        exit
    }
    END { if (!found) exit 1 }
    ' "$config_file")

    if [[ -z "$value" ]]; then
        echo "❌ 错误：无法从 $config_file 中读取 [$section] $key" >&2
        exit 1
    fi

    echo "$value"
}

# =====================================================
# 初始化环境变量
# =====================================================
init_build_env() {
    local SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[1]}")" && pwd)"
    local CONFIG_DIR="$(dirname "$(dirname "$SCRIPT_DIR")")/configs"
    local PROJECT_CONFIG_FILE="$CONFIG_DIR/$PROJECT_CONF_FILE"

    echo "🔧 配置文件目录: $CONFIG_DIR"

    if [[ ! -f "$PROJECT_CONFIG_FILE" ]]; then
        echo "❌ 错误：配置文件 $PROJECT_CONFIG_FILE 不存在" >&2
        exit 1
    fi

    export ROOT_PATH=$(get_config_value "$PROJECT_CONFIG_FILE" "system" "root_path")
    export PROJECT_NAME=$(get_config_value "$PROJECT_CONFIG_FILE" "system" "server_name")
    export SECOND_ROOT_PATH=$(get_config_value "$PROJECT_CONFIG_FILE" "system" "second_root_path")


    echo "✅ ROOT_PATH = $ROOT_PATH"
    echo "✅ SECOND_ROOT_PATH = $SECOND_ROOT_PATH"
    echo "✅ PROJECT_NAME = $PROJECT_NAME"

    export ROOT_PATH PROJECT_NAME SECOND_ROOT_PATH
}

# =====================================================
# 检查 Docker Compose
# =====================================================
check_docker_compose() {
    if ! command -v docker &> /dev/null; then
        echo "❌ 错误：docker 未安装或不在 PATH 中" >&2
        exit 1
    fi

    if docker compose version &> /dev/null; then
        DOCKER_COMPOSE="docker compose"
    elif docker-compose version &> /dev/null; then
        DOCKER_COMPOSE="docker-compose"
    else
        echo "❌ 错误：未找到 'docker compose' 或 'docker-compose'" >&2
        exit 1
    fi

    export DOCKER_COMPOSE
}

# =====================================================
# 停止服务（通用）
# =====================================================
stop_service() {
    local mode=$1
    local profile="${PROJECT_NAME}-${mode}"
    local temp_compose_file="./docker-compose.generated.yml"

    # 生成替换后的 compose 文件
    sed -e "s#{PROJECT_NAME}#${PROJECT_NAME}#g" \
        -e "s#{ROOT_PATH}#${ROOT_PATH}#g" \
        -e "s#{SECOND_ROOT_PATH}#${SECOND_ROOT_PATH}#g" \
        docker-compose.yml > "$temp_compose_file"

    echo "🛑 正在停止 profile: $profile"



    if ! $DOCKER_COMPOSE -f "$temp_compose_file" --profile "$profile" ps &> /dev/null; then
        echo "🔍 未发现 profile '$profile' 的服务，跳过停止。"
        rm -f "$temp_compose_file"
        return 0
    fi

    $DOCKER_COMPOSE -f "$temp_compose_file" --profile "$profile" down -t 10 > /dev/null 2>&1

    if [ $? -eq 0 ]; then
        echo "✅ profile '$profile' 已停止并删除容器。"
    else
        echo "⚠️  停止 profile '$profile' 时出现警告。"
    fi

}

# =====================================================
# 启动服务（通用）
# =====================================================
start_service() {
    local mode=$1
    local profile="${PROJECT_NAME}-${mode}"
    local temp_compose_file="./docker-compose.generated.yml"

    echo "🚀 启动服务 (mode: $mode, profile: $profile)"

    sed -e "s#{PROJECT_NAME}#${PROJECT_NAME}#g" \
        -e "s#{ROOT_PATH}#${ROOT_PATH}#g" \
        -e "s#{SECOND_ROOT_PATH}#${SECOND_ROOT_PATH}#g" \
        docker-compose.yml > "$temp_compose_file"

    if [ $? -ne 0 ]; then
        echo "❌ 生成 compose 文件失败"
        exit 1
    fi

    cat docker-compose.generated.yml

    stop_service "$mode"

    $DOCKER_COMPOSE -f "$temp_compose_file" --profile "$profile" up -d
    local exit_code=$?

    rm -f "$temp_compose_file"

    if [ $exit_code -eq 0 ]; then
        echo "✅ 服务 '$profile' 启动成功。"
    else
        echo "❌ 服务 '$profile' 启动失败。"
        exit 1
    fi
}

# =====================================================
# 重启服务（通用）
# =====================================================
restart_service() {
    local mode=$1
    stop_service "$mode"
    start_service "$mode"
}

# =====================================================
# 执行指定操作（主入口）
# =====================================================
run_mode() {
    local mode=$1
    local action=$2

    # 打印当前工作目录（调试用）
    echo "📁 当前工作目录: $(pwd)"

    # 校验参数
    if [[ -z "$mode" || -z "$action" ]]; then
        echo "📌 用法: run_mode <cpu|gpu> <start|stop|restart>"
        exit 1
    fi

    if [[ ! "$mode" =~ ^(cpu|gpu)$ ]]; then
        echo "❌ 错误：mode 必须是 'cpu' 或 'gpu'" >&2
        exit 1
    fi

    case "$action" in
        start|stop|restart)
            ;;
        *)
            echo "❌ 错误：action 必须是 'start', 'stop', 或 'restart'" >&2
            exit 1
            ;;
    esac

    # 检查文件
    if [ ! -f "docker-compose.yml" ]; then
        echo "❌ 错误：当前目录下未找到 docker-compose.yml 文件" >&2
        exit 1
    fi

    # 初始化环境和 Docker
    init_build_env
    check_docker_compose

    # 执行操作
    case "$action" in
        start)
            start_service "$mode"
            ;;
        stop)
            stop_service "$mode"
            # 不要放到stop方法中，否则，启动先调用停止，会导致yml找不到
            rm -f "./docker-compose.generated.yml"

            ;;
        restart)
            restart_service "$mode"
            ;;
    esac

    echo "🎉 $mode 模式 $action 操作完成。"
}
